package com.tek.ding.faceding.network.rx;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;

import cn.pedant.SweetAlert.SweetAlertDialog;


public class ProgressDialogHandle extends Handler {
    public static final int SHOW_DIALOG = 1;
    public static final int DISMISS_DIALOG = 0;

    private SweetAlertDialog sweetAlertDialog;

    private Context context;
    private boolean cancelable;
    public OnProgressDialogListener onProgressDialogListener;

    public ProgressDialogHandle(Context context) {
        this(context, false, null);
    }

    public ProgressDialogHandle(Context context, boolean cancelable, OnProgressDialogListener onProgressDialogListener) {
        super();
        this.context = context;
        this.cancelable = cancelable;
        this.onProgressDialogListener = onProgressDialogListener;

        initProgressDialog();
    }

    private void initProgressDialog() {
        if (sweetAlertDialog == null) {
            sweetAlertDialog = new SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE);
            sweetAlertDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
            sweetAlertDialog.setTitleText("加载中...");
        }
        if (cancelable) {
            sweetAlertDialog.setCancelText("关闭");
            sweetAlertDialog.setCancelClickListener(sweetAlertDialog -> {
                sweetAlertDialog.cancel();
                if (onProgressDialogListener != null) {
                    onProgressDialogListener.onCancelProgress();
                }
            });
        }
    }

    public void showProgressDialog() {
        if (sweetAlertDialog != null && !sweetAlertDialog.isShowing()) {
            sweetAlertDialog.show();
        }
    }

    public void dismissProgressDialog() {
        if (sweetAlertDialog != null && sweetAlertDialog.isShowing()) {
            sweetAlertDialog.dismiss();
            sweetAlertDialog = null;
        }
    }

    @Override
    public void handleMessage(@NonNull Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case SHOW_DIALOG:
                showProgressDialog();
                break;
            case DISMISS_DIALOG:
                dismissProgressDialog();
                break;
            default:
                break;
        }
    }

    public interface OnProgressDialogListener {
        void onCancelProgress();
    }
}
